<template>
    <el-select
      :value="localValue"
      :disabled="disabled"
      @change="onSelectedChange"
      :placeholder="placeholder||hint"
      :clearable="clearable"
      :filterable="filterable"
      :allow-create="allowCreate">
      <el-option
        v-for="item in list"
        :key="item[id]"
        :label="item[name]"
        :value="nameType === 'int' ? parseInt(item[id]) : item[id]"
      />
    </el-select>
</template>

<script>
export default {
  name: "ApiSelect",
  props: {
    id: {
      type: String,
      default: "id"
    },
    name: {
      type: String,
      default: "name"
    },
    nameType: {
      type: String,
      default: "int"
    },
    clearable: {
      type: Boolean,
      default: true
    },
    filterable: {
      type: Boolean,
      default: false
    },
    allowCreate: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    options: {
      type: Array,
      default: null
    },
    api: {
      type: Function,
      default: null
    },
    params: {
      type : Object
    },
    value : {
      type: [Number,String],
      require: true
    },
    selectedRow: {
      type: Object,
      default: null
    },
    onChange: {
      type: Function,
      default: null
    },
    placeholder : String,
    hint: String
  },
  data() {
    return {
      list: [
      ],
      localValue: this.value
    }
  },
  created(){
    if(this.options){
      this.list = this.options;
      console.log("apiSelect.created() apiSelectItems options",this.list)
      return;
    }
    if(!this.api){
      console.warn("apiSelect.created() ApiSelect的api属性和options属性同时为空");
      return;
    }
    let callback = res=>{
      if(res.data){
        this.list = res.data.list ? res.data.list : res.data;
      }else if(res.rows){
        this.list = res.rows;
      }else if(res.result){
        this.list = res.result;
      }
      console.log("apiSelect.created() apiSelectItems api result",this.list);
    };
    if(this.params){
      this.api(this.params).then(callback);
    }else{
      this.api().then(callback);
    }
  },
  watch: {
    value(val){
      this.localValue = val;
    },
    options(val){
      console.log("apiSelect.watchOptions() apiSelectItems options change",val);
      this.list = val;
    },
  },
  methods: {
    onSelectedChange(val){
      this.localValue = val;
      this.$emit("update:value",val);
      // id可能是string类型所以这里必须使用==或把id转成int在比较
      // noinspection EqualityComparisonWithCoercionJS
      let row = this.list.find(item=>item[this.id]==val);
      this.$emit("update:selectedRow",row);
      if(this.onChange){
        this.onChange(row);
      }
    }
  },
};
</script>
